package com.starblink.library.widget.wishlist

import android.app.Activity
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.BarUtils
import com.google.android.material.snackbar.Snackbar
import com.starblink.android.basic.ext.toastUI
import com.starblink.android.basic.extension.dp2px
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.R
import com.starblink.library.widget.databinding.ToastAdd2WishlistBinding
import java.lang.ref.WeakReference

/**
 *
 * Create by yuanl at 2023/04/08
 */
object WishlistToast {

    private var snackBarRef: WeakReference<Snackbar>? = null

    fun toast(activity: Activity, productId: String) {

        val toCreateWish = fun(pid: String) {
            toastUI("wishlist developing, product id is: $pid")
        }

        if (snackBarRef?.get()?.isShown == true) {
            (snackBarRef?.get()?.view as Snackbar.SnackbarLayout?)?.run {
                findViewById<View>(R.id.btn_add)?.setOnClickListener {
                    toCreateWish.invoke(productId)
                }
            }
            return
        }

        val binding = ToastAdd2WishlistBinding.inflate(LayoutInflater.from(activity))
        binding.btnAdd.setOnClickListener {
            toCreateWish.invoke(productId)
        }

        val snack = Snackbar.make(activity.window.decorView, "", Snackbar.LENGTH_LONG)
            .addCallback(object : Snackbar.Callback() {
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    super.onDismissed(transientBottomBar, event)
                    snackBarRef?.clear()
                    snackBarRef = null
                }
            }).setAnimationMode(Snackbar.ANIMATION_MODE_FADE)
        snack.show()
        (snack.view as Snackbar.SnackbarLayout?)?.run {
            setPadding(16.dp2px(), 0, 16.dp2px(), 0)
            setBackgroundColor(Color.TRANSPARENT)
            addView(binding.root,
                ViewGroup.MarginLayoutParams(
                    ViewGroup.MarginLayoutParams.MATCH_PARENT,
                    48.dp2px(),
                ).apply {
                    bottomMargin = 60.dp2px() + CommUtils.getBottomStatusHeight()
                })
        }
        snackBarRef = WeakReference(snack)
    }

    fun Activity.toastAddWishlist(productId: String) {
        toast(this, productId)
    }


    fun Fragment.toastAddWishlist(productId: String) {
        activity ?: return
        toast(this.requireActivity(), productId)
    }


}